package com.itfreer.data.general.interceptor.defulat;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

import com.itfreer.data.general.Field;
import com.itfreer.data.general.IQueryMap;
import com.itfreer.data.general.ITable;
import com.itfreer.data.general.QueryMap;
import com.itfreer.data.general.RowBase;
import com.itfreer.data.general.interceptor.DbEditInterceptorClass;
import com.itfreer.data.general.interceptor.DbEditType;

/**
 * 唯一值检查
 */
public class UniqueCheckInterceptor extends DbEditInterceptorClass {

	public UniqueCheckInterceptor() {
		super.setIndex(-80);
	}

	@Override
	public void BeforeDbEditOption(ITable table, Object editEntitys,
			DbEditType editType) {
		if (editType == DbEditType.Insert || editType == DbEditType.Update) {
			Field[] uniqueFields = table.getUniqueFields();
			if (uniqueFields == null || uniqueFields.length <= 0)
				return;

			if (editEntitys instanceof RowBase) {
				uniqueCheck(table, (RowBase) editEntitys);
			} else {
//                LogUtils.e("【UniqueCheckInterceptor】  非单一RowBase保存，不处理唯一值检查！");
			}
		}
	}

	@Override
	public void DbEditOptionException(ITable table, Object editEntitys,
			DbEditType editType, Exception ex) {
	}

	@Override
	public void AfterDbEditOption(ITable table, Object editEntitys,
			DbEditType editType) {
	}

	@Override
	public String getInterceptorName() {
		return "唯一值检查";
	}

	protected void uniqueCheck(ITable table, RowBase entity) {
		HashMap<String, List<Field>> uniqueFieldMap = table.getUniqueFieldMap();
		if (uniqueFieldMap == null || uniqueFieldMap.size() <= 0) {
			return;
		}
		String guidField = table.getGUIDFieldName();
		Object guidValue = entity.getValue(guidField);
		Set<String> uniqueFields = uniqueFieldMap.keySet();
		IQueryMap queryMap = new QueryMap();
		queryMap.setSelectFields("count(1)");
		queryMap.getWhereMap().put(guidField + ":!=", guidValue);
		String fieldNames = "";
		for (String key : uniqueFields) {
			List<Field> fields = uniqueFieldMap.get(key);
			for (Field item : fields) {
				queryMap.getWhereMap().put(item.getFieldName(),
						entity.getValue(item.getFieldName()));
				fieldNames += item.getFieldAliasName() + "+";
			}
		}
		Object obj = table.getExecuteScalar(queryMap);
		if (obj != null) {
			fieldNames = fieldNames.substring(0, fieldNames.length() - 1);
			int count = Integer.parseInt(obj.toString());
			if (count > 0) {
				throw new UniqueCheckException(fieldNames + "值不唯一！");
			}
		}
	}
}